package com.mx.base.language.script

import org.apache.poi.ss.usermodel.WorkbookFactory
import java.io.File


/**
 * @author: xiao.ma
 * Date: 2022/3/28 17:33
 * Desc:
 */

object ExcelHelper {

    /**
     * 从Excel读取国家化语言包
     * @param excelFilePath excel文件路径
     * @return
     */
    fun readLanguageFromExcel(
        excelFilePath: String,
        target: List<String>
    ): MutableMap<String, MutableMap<String, String>> {
        val languageMap = mutableMapOf<String, MutableMap<String, String>>()
        val workbook = WorkbookFactory.create(File(excelFilePath))
        workbook.sheetIterator().forEach { sheet ->
            println("====>${sheet.sheetName}")
            val header = sheet.getRow(0)
            if (header != null) {
                val firstRowIndex = sheet.firstRowNum + 2 //前两行是values- 和对应语言翻译所以不读
                val lastRowIndex = sheet.lastRowNum
                for (rowIndex in firstRowIndex..lastRowIndex) {
                    val row = sheet.getRow(rowIndex)
                    if (row != null) {
                        val firstCellNum = row.firstCellNum
                        val lastCellNum = row.lastCellNum
                        val key = row.getCell(firstCellNum.toInt())?.stringCellValue
                        // println("==>key=$key")
                        if (key != null) {
                            for (index in firstCellNum + 1 until lastCellNum) {

                                val mapKey = header.getCell(index)?.stringCellValue
                                if (mapKey != null
                                    && mapKey.startsWith("values")
                                    && (target.contains(mapKey) || target.isEmpty())//如果目标翻译为空则默认加载所有语言包
                                ) {
                                    var translateMap = languageMap[mapKey]
                                    if (translateMap == null) {
                                        println("------>init $mapKey translateMap")
                                        translateMap = mutableMapOf()
                                        languageMap[mapKey] = translateMap
                                    }
                                    val languageValue = row.getCell(index)?.stringCellValue
                                    if (languageValue != null && translateMap[key] == null) {
                                        translateMap[key] = languageValue
                                    }
                                }
                            }
                        }
                    }

                }
            }
        }
        workbook.close()
        return languageMap
    }
}